﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Web;
using System.Diagnostics;

namespace SmartMap.Domain.Handlers
{
	public class SmartMapBaseHandler
	{
		private HttpContext _context;
		private const string handlerNamespace = "SmartMap.Domain.Handlers.";

		protected HttpRequest CurrentRequest
		{
			[DebuggerStepThrough()]
			get
			{
				return _context.Request;
			}
		}

		protected HttpContext CurrentContext
		{
			[DebuggerStepThrough()]
			get
			{
				return _context;
			}
		}

		public string Action
		{
			[DebuggerStepThrough()]
			get
			{
				return CurrentRequest.Params["action"];
			}
		}

		private string _output;
		public virtual string Output
		{
			get
			{
				return _output;
			}
		}

		protected SmartMapBaseHandler(HttpContext context)
		{
			_context = context;
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected void Dispose(bool disposing)
		{
		}

		~SmartMapBaseHandler()
		{
			Dispose(false);
		}

		public void Execute()
		{
			// Get the desired method by name: DisplayName
			MethodInfo methodInfo =
			   this.GetType().GetMethod(this.Action);

			// Use the instance to call the method without arguments
			methodInfo.Invoke(this, null);

		}

		protected string ToJson(object target)
		{
			JavaScriptSerializer s = new JavaScriptSerializer();
			return s.Serialize(target);
		}

		public static SmartMapBaseHandler GetHandler()
		{
			string handler = handlerNamespace + HttpContext.Current.Request.Params["handler"];
			string assemblyName = Assembly.GetAssembly(typeof(SmartMapBaseHandler)).FullName;

			SmartMapBaseHandler baseObject = Activator.CreateInstance(assemblyName, handler).Unwrap() as SmartMapBaseHandler;

			return baseObject;

		}
	}
}
